import { observable, action, toJS } from 'mobx';
import * as Detail from '../apis/detail';
import * as detailForm from '../apis/detailForm';
import { message, Modal } from 'antd';
import { WeaLocaleProvider } from 'ecCom';

const { confirm } = Modal;
import { WeaTableNew, WeaForm } from 'comsMobx';
import DocDetailConstant from '../util/DocDetailConstant';

const getLabel = WeaLocaleProvider.getLabel;
const { TableStore } = WeaTableNew;

const getParams = (prop) => {
  const { conditionType, domkey, defaultValue, show } = prop;
  if (show && conditionType) return { [domkey[0]]: defaultValue || '' };
  return {};
};
class DetailFormStore {
  @observable title = getLabel(1986, '新建文档');// index.jsp
  @observable docSubject = '';
  @observable doccontent = '';
  @observable loading = false;
  @observable tabKey = '0';
  @observable footConfig = [];
  @observable rightMenus = [];
  @observable property = [];
  params = {};// 存一下默认值
  @observable fileList = [];
  @observable form = new WeaForm();
  @observable fileVersionTableStore = new TableStore();
  @observable shareTableStore = new TableStore();
  @observable shareAddEditBtn = {};
  @observable conditions= [];
  @observable isClickSubmit = false;
  @observable canShowBJCA = false; // 是否可以展示北京capdf插件
  @observable reply={
    replyable: '0',
    replyremind: '0',
  };
  @observable mainImagefile = '';
  @observable mainfileLocal='';
  @observable fileTypeList = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'doc', 'docx', 'xls', 'xlsx'];
  @observable isAdd = false;
  @action
  doLoading = (loading) => {
    this.loading = loading;
    this.isClickSubmit = false;
  }
  @action
  setTabKey = (tabKey = 0) => {
    this.tabKey = tabKey;
  };
  @action
  setDatas = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
    return this;
  }
  @action
  setDocContent = (docContent) => {
    this.doccontent = docContent;
  }
  @action
  setMainImagefile = (val) => {
    this.mainImagefile = val;
  }
  @action
  setReplyKey = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this.reply[key] = params[key];
    });
    return this;
  }
  // 获取标题
  @action
  getBasic = (params = {}) => {
    this.loading = true;
    detailForm.getBasic(params).then(action((data) => {
      this.setBasic(data);
      this.setReplyKey({ replyable: data.replyable, replyremind: data.replyremind });
      this.setMainImagefile(data.mainimagefile);
      if (data.canShowBJCA === '1') {
        this.canShowBJCA = true;
      }
      this.loading = false;
    }));
  };

  @action
  setBasic = (params = {}) => {
    this.rightMenus = params.rightMenus || this.rightMenus;
    this.docSubject = params.docSubject;
    // this.loading = false;
  };

  // 获取富文本内容
  @action
  getHtmlContent = (params = {}, module = false) => {
    this.loading = true;
    detailForm[module ? 'getModuleContent' : 'getHtmlContent'](params).then(action((data) => {
      this.doccontent = data.content ? data.content : this.doccontent;
      this.docSubject = data.title ? data.title : this.docSubject;
      this.loading = false;
    }));
  };

  // 获取附件列表
  @action
  getFileList = (params = {}) => {
    this.loading = true;
    detailForm.getFileList(params).then(action((data) => {
      this.updateFileList(data.dataList);
      this.mainfileLocal = data.mainfileLocal;
      this.fileTypeList = data.fileTypeList;
    }));
  };

  // 富文本底部工具栏
  @action
  getEditSet = (params = {}) => {
    this.loading = true;
    detailForm.getEditSet(params).then(action((data) => {
      this.footConfig = data.footConfig;
      this.loading = false;
    }));
  };

  // 获取属性
  @action
  getProperty = (params = {}) => {
    this.loading = true;
    detailForm.getProperty(params).then(action((data) => {
      if (data.status == -1) {
        message.error(data.msg);
        return;
      }
      let hasMouldParam = false;
      const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
      data.data.forEach((item) => {
        if (item.paramForm && item.paramForm.domkey && item.paramForm.domkey[0] === 'selectedPubMouldId') {
        	if (!idReg) { // 新建时才获取模板内容
          		this.getHtmlContent({ mouldid: item.paramForm.defaultValue, secid: params.secid }, true);
          		hasMouldParam = true;
          	}
        } else if (item.paramForm && item.paramForm.conditionType == 'TEXTAREA' && item.paramForm.defaultValue) {
          item.paramForm.defaultValue = item.paramForm.defaultValue.replace(/<br>/g, '\n');
        }
      });
      this.setProperty(data.data);
      if (!idReg && !hasMouldParam) {
      		this.getHtmlContent({ secid: params.secid }, true);
      }
    }));
  };

  // 设置属性
  @action
  setProperty = (property = []) => {
    this.form = new WeaForm();
    this.loading = false;
    this.property = property;
    this.params = (function () {
      let params = {};
      property.forEach((prop) => {
        if (prop.paramForm && prop.paramForm.conditionType) {
          params = { ...params, ...getParams(prop.paramForm) };
        }
      });
      return params;
    }());
    let items = property.map(item => item.paramForm);
    this.form.initFormFields([{ items }]);
    this.form.updateFields(toJS(this.params));
  };

  /**
   * 属性页修改文档编辑模板时触发的onChange
   * @param id
   */
  @action
  changeSelectedPubMouldId = (e, value) => {
    const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
    const id = value.value ? value.value : value;
    if (!idReg) {
      confirm({
        title: getLabel(131329, '信息确认'),
        content: getLabel(81566, '本目录绑定了编辑模板，加载编辑模板可能会导致文档内容丢失，建议先复制下文档内容，确定要继续吗？'),
        onOk: () => {
          const officeReg = window.location.search.match(/(\?|\&)isOffice=\d+/g);
          const isOffice = officeReg && officeReg.length === 1 ? officeReg[0].split('=')[1] : '';
          isOffice ? window.changeOfficeMould(id)
            : this.getHtmlContent({ mouldid: id }, true);
        },
        onCancel: () => {

        },
      });
    }
  }

  /**
   * 属性页修改文档目录时触发的onChange
   * @param params
   */
  @action
  changeSecCategory = (params) => {
    let id = params.seccategory.value;
    if (!id) {
      this.form.updateFields({ ...params });
      return;
    }
    confirm({
      title: getLabel(131329, '信息确认'),
      content: getLabel(81565, '切换目录会清除文档属性和附件，确定要继续吗？'),
      onOk: () => {
        this.getProperty({ seccategory: id });
		const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
        let docid = idReg && idReg.length === 1 ? idReg[0].split('=')[1] : '';
        this.getEditSet({ id: docid, seccategory: id });
      },
      onCancel: () => {
        let seccategory = this.params.seccategory;
        this.getProperty({ seccategory });
      },
    });
  }

  /**
   * 属性页修改发布类型时触发的onChange
   * @param value
   */
  @action
  changeDocPublishType = (value) => {
    const showDocmain = value.docPublishType.value === '2';
    const property = toJS(this.property).map((prop) => {
      if (prop.paramForm.domkey[0] === 'docmain') {
         prop.paramForm = { ...prop.paramForm, show: showDocmain };
      }
      return prop;
    });
    // this.setProperty(property);


    this.property = property;

    if (!showDocmain) {
      let formDatas = this.form.getFormDatas();
      formDatas.docmain = { value: '' };
      this.form.updateFields(formDatas);
    }
  }

  /**
  *属性页修改密级时触发的onChange
  *@param value
  */
 @action
 changeSecretLevel = (value) => {
  	if (this.footConfig && this.footConfig.length > 0) {
  		this.footConfig.forEach((item) => {
  			if (item.name === 'Browser') {
  				if (!item.dataParams) {
  					item.dataParams = {};
  				}
  				item.dataParams.secretLevel = value.secretLevel.value;
  			}
  		});
  	}
  }

  // 提交验证
  @action
  isExists = (params = {}, callback) => {
    detailForm.isExists(params).then((data) => { callback(data); });
  };

  // 提交表单
  @action
  doSubmit = (params = {}) => {
    this.loading = true;
    if (this.canShowBJCA) {
      params = { ...params, saveBJCA: '1' };
    }
    params = { ...params, mainimagefile: this.mainImagefile };
    params = this.reply.replyable === '1' ? { ...params, replyremind: this.reply.replyremind } : { ...params, replyremind: '0' };
    detailForm.doSubmit(params).then(action((data) => {
      if (params.isflowdoc == 1) {
        this.loading = false;
        const flowdocObj = params.flowdocObj;
        flowdocObj.status = data.status;
        if (flowdocObj.status === 1) {
            window.saveDocDetail(flowdocObj);
        } else {
            flowdocObj.msg = data.msg;
            window.saveDocDetail(flowdocObj);
        }
      } else {
        data.status === 1 && data.link ? window.location.href = data.link : message.error(data.msg);
      }
    }));
  };

  // 保存图片缓存
  @action
  saveFilesTmp = (params = {}) => { detailForm.saveFilesTmp(params); };
  // 更新附件列表
  @action
  updateFileList = (fileList = []) => {
    let fileTypeList = toJS(this.fileTypeList);
    let _fileList = [];
    let flag = true;
    let mainfileExit = false; // 记录主附件是否已经被删除
    let firstfile = -1; // 记录第一个支持设置为主附件的位置
    fileList.forEach((val, index) => {
      let filetype = val.fileExtendName || '';
      for (let i = 0; i < fileTypeList.length; i++) {
        if (filetype && fileTypeList[i] && filetype.toUpperCase() == fileTypeList[i].toUpperCase()) {
          val = { ...val, ReadOnline: '1' };
          if (this.isAdd && !this.mainfileLocal && flag) {
            this.mainfileLocal = index.toString();
            this.mainImagefile = val.fileid;
            flag = false;
          }
          break;
        }
      }
      if (this.mainfileLocal && this.mainImagefile == val.fileid) {
        this.mainfileLocal = index.toString();
      }
      if (this.mainImagefile == val.fileid) {
        mainfileExit = true;
      }
      _fileList.push(val);
    });
    this.fileList = _fileList;
    let mainvalue = false; // 记录被删除的主附件后边是否有支持设置为主附件的附件
    if (!mainfileExit) { // 主附件不存在，说明没有朱附件
      fileList.forEach((val, index) => {
        let filetype = val.fileExtendName || '';
        for (let i = 0; i < fileTypeList.length; i++) {
          if (filetype && fileTypeList[i] && filetype.toUpperCase() == fileTypeList[i].toUpperCase()) {
            if (firstfile < 0) { // 记录附件列表上第一个支持设置为主附件的位置
              firstfile = index;
            }
            // 查找当前被删除的主附件后边有没有支持设置为主附件的附件
            if ((this.mainImagefile <= val.fileid || this.mainfileLocal <= index) && !mainvalue) {
              this.mainfileLocal = index.toString();
              mainvalue = true;
              break;
            }
            // break;
          }
        }
      });
      if (!mainvalue) { // 如果当前附件后边没有可以当做主附件的附件，则将第一个设置为主附件
        this.mainfileLocal = firstfile.toString();
      }
    }
    this.loading = false;
  };

  @action
  deleteFileEdition = (params = {}, callback) => {
    detailForm.deleteFileEdition(params).then((data) => {
      callback(data);
    });
  }

  @action
  searchFileVersion = (params) => {
    this.loading = true;
    Detail.getFileVersion(params).then(action((result) => {
      this.fileVersionTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  @action
  searchShare = (params) => {
    this.loading = true;
    Detail.getShareTable(params).then(action((result) => {
      this.shareTableStore.getDatas(result.sessionkey, params.current || 1);
      this.loading = false;
    }));
  }

  // 获取共享条件
  @action
  canShareAddEdit = (params = {}) => {
    Detail.canShareAddEdit(params).then(action((data) => {
      this.shareAddEditBtn = data;
    }));
  };

  // 删除共享条件
  @action
  deleteShare = (params = {}) => {
    Detail.deleteShare(params).then(action((data) => {
      data.status === 1
        ? this.searchShare({ id: params.docid })
        : message.warning(data.msg);
    }));
  };

  // 获取共享条件
  @action
  doShareAddSubmit = (params = {}) => {
    Detail.doShareAddSubmit(params).then(action((data) => {
      data.status === 1 &&
      this.searchShare({ id: params.id });
    }));
  };

  // 获取共享条件
  @action
  getAddShare = (params = {}) => {
    Detail.getAddShare(params).then(action((data) => {
      this.conditions = data.conditions;
    }));
  };

  @action
  docfileCheckIn = (docid) => {
    detailForm.docfileCheckIn({ id: docid });
  }
}

export default DetailFormStore;
